<template>
  <div class="content-wrap content-container" v-loading="loading">
    <el-table :data="allRequirements" style="width: 100%; overflow-y: auto;" height="750" border stripe >
      <el-table-column
          fixed
          type="index"
          label="序号"
          width="60"
          align="center"
        ></el-table-column>
      <el-table-column prop="requirementName" label="需求名称">
        <template #="{row}">
          <p class="table-requirement-name" @click="handleRowClick(row.id)">{{ row.requirementName }}</p>
        </template>
      </el-table-column>
      <el-table-column prop="RequirementManagerName" label="项目经理" align="center" width="120">
        <template #="{row}">
          <span>{{ row.RequirementManagerName }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="requirementBossName" label="技术负责人" align="center" width="120">
        <template #="{row}">
          <span>{{ row.requirementBossName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" align="center">
        <template #default="{row}">
          <el-button type="primary" plain size="small" @click="handleRowEvaluate(row)" :disabled="row.itemRequirementChilds.length == 0">评价</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 评价弹窗 -->
    <el-dialog
      v-model="dialogEvaluateVisible"
      title="评价"
      :close-on-click-modal="false"
      @close="handleCloseEvaluateDialog"
      @closed="handleCloseEvaluateDialog"
    >
      <el-form ref="managerRequirementRef" :model="managerRequirementForm" :rules="managerRequirementRules">
        <!-- 项目经理对技术负责人评分配比 -->
        <el-form-item label="项目经理对技术负责人评分配比：" prop="mToBAvgNumber" label-width="240px" required :rules="managerRequirementRules.mToBAvgNumber">
          <el-input-number type="number" min="0" size="default" v-model="managerRequirementForm.mToBAvgNumber"></el-input-number>
          （备注：任务分值：1-100；在这个任务中技术负责人，有没有帮我，帮我多少）
        </el-form-item>
        <!-- 项目经理对技术负责人评分 -->
        <el-form-item label="对技术负责人的评分：" prop="mToDevBossNumber" label-width="170px" >
          <el-input-number type="number" min="0" max="100" size="default" v-model="managerRequirementForm.mToDevBossNumber"></el-input-number>
          （备注：评分分值：1-100；针对这个需求，技术负责人在处理时是否积极，解决问题，沟通等等...）
        </el-form-item>
        <el-form-item label="对技术负责人的评语：" prop="mToDevBossTip" label-width="170px" required>
          <el-input type="textarea" ::autosize="{ minRows: 1, maxRows: 4 }" clearable placeholder="请输入对技术负责人的评价" v-model="managerRequirementForm.mToDevBossTip"></el-input>
        </el-form-item>
        <!-- 项目经理对研发评分 -->
        <div v-for="(item, index) in managerRequirementForm.devs" :key="index">
          <el-form-item :prop="'managerRequirementForm.' + index + '.mToDevNumber'" :label="`对${item.userName}的评分：`" label-width="170px" >
            <el-input-number type="number" min="0" size="default" v-model="item.mToDevNumber"></el-input-number>
            （备注：评分分值：1-100；针对这个任务，研发在处理时是否积极，沟通解决问题，延期等等...）
          </el-form-item>
          <el-form-item :prop="'managerRequirementForm.' + index + '.mToDevTip'" :label="`对${item.userName}的评语：`" label-width="170px">
              <el-input type="textarea" ::autosize="{ minRows: 1, maxRows: 4 }" clearable :placeholder="`请输入对${item.userName}的评语`" v-model="item.mToDevTip"></el-input>
          </el-form-item>
        </div>

        <el-form-item>
          <div class="dialog-form-footer">
            <el-button type="default" @click="handleCloseEvaluateDialog">取消</el-button>
            <el-button type="primary" @click="handleSubmitEvaluate(managerRequirementRef)">提交</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 需求详情弹窗 -->
    <el-dialog style="width: 1200px;" :close-on-click-modal="false" v-model="dialogInfoVisible" @close="dialogInfoVisible = false"  @closed="dialogInfoVisible = false" top="8vh">
        <CommonRequirementInfoVue :isRequirementID="isRequirementID" :clearData="clearData" :isComment="true"></CommonRequirementInfoVue>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import { ref, onMounted, reactive } from 'vue'
import { GetManagerNoToDevRequirements, SaveManagerNoToDevRequirements } from "@/api/newDemands/index";
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import CommonRequirementInfoVue from "@/components/requirement/comomRequirementInfo.vue";
import { validateInput, isValidateString } from "@/utils/utils";

const loading = ref(false);
const isRequirementID = ref<any>(null); //当前操作任务ID
const dialogInfoVisible = ref(false);//查看需求弹窗控件
const clearData = ref(false);//控制是否清空子组件数据
const dialogEvaluateVisible = ref(false);//控制评分弹窗
const allRequirements = ref<any>([]);// 项目经理所有未评价需求
const managerRequirementRef = ref<FormInstance>();
const managerRequirementRules = reactive({
  mToDevBossNumber: [{ required: true, message: '必填', trigger: 'blur' }],
  mToDevBossTip: [{ required: true, message: '必填', trigger: 'blur', validator: validateInput }],
  mToBAvgNumber: [{ required: true, message: '必填', trigger: 'blur' }],
  // devs: [
  //   {
  //     mToDevNumber: [{ required: true, message: '必填', trigger: 'blur' }],
  //     mToDevTip: [{ required: true, message: '必填', trigger: 'blur', validator: validateInput }],
  //   }
  // ]
});
// const rules = reactive({
//   mToDevNumber: [{ required: true, message: '必填', trigger: 'blur' }],
//   mToDevTip: [{ required: true, message: '必填', trigger: 'blur', validator: validateInput }],
// })


const managerRequirementForm = ref<any>({
  id: null,
  mToDevBossNumber: 0,// 项目经理对技术负责人的评分
  mToDevBossTip: "",// 项目经理对技术负责人的评论
  mToBAvgNumber: 0,// 项目经理对技术负责人评分配比
  devs: [{
      itemRequirementChildId: null,// 研发任务id
      mToDevNumber: 0,// 项目经理对研发的评分
      mToDevTip: "",// 项目经理对研发的评论
      userName: "",// 研发人员
      userUUID: "",// 研发人员uuid
    }]
  }
);// 项目经理评价数据

// TODO 获取项目经理未评价需求
const getAllRequirements = async () => {
  loading.value = true;
  const { data } = await GetManagerNoToDevRequirements();
  if (data.code === 200 && data.data !== null) {
    allRequirements.value = data.data;
    console.log("获取数据：", allRequirements.value);
    ElMessage.success(data.msg);
  } else if (data.code === 200 && data.data == null) {
    ElMessage.warning("暂无数据");
    loading.value = false;
    return;
  } else {
    ElMessage.error(data.msg);
    loading.value = false;
    throw console.error(data.msg);
  };

  loading.value = false;
};

// TODO 开启评价弹窗
const handleRowEvaluate = async (data: any) => {
  dialogEvaluateVisible.value = true;
  managerRequirementForm.value.id = data.id;
  managerRequirementForm.value.devs = data.itemRequirementChilds.map((item: any) => {
    return {
      itemRequirementChildId: item.itemRequirementChildId,
      mToDevNumber: item.mToDevNumber == '' ? 0 : Number(item.mToDevNumber),
      mToDevTip: item.mToDevTip,
      userName: item.userName,
      userUUID: item.userUUID
    }
  });
  console.log("待评价：", managerRequirementForm.value);
};

// TODO 关闭评价弹窗
const handleCloseEvaluateDialog = () => {
  dialogEvaluateVisible.value = false;
  managerRequirementForm.value = {
    id: null,
    mToDevBossNumber: 0,
    mToDevBossTip: "",
    mToBAvgNumber: 0,
    devs: [{
        itemRequirementChildId: null,
        mToDevNumber: 0,
        mToDevTip: "",
        userName: "",
        userUUID: "",
      }]
  }
  managerRequirementRef.value?.resetFields();
  console.log("清空数据：", managerRequirementForm.value);
};

// TODO 查看需求
const handleRowClick = async (id: number) => {
  isRequirementID.value = id;
  console.log(isRequirementID.value)
  dialogInfoVisible.value = true;
};

// TODO 提交评价
const handleSubmitEvaluate = async (formEl: FormInstance | undefined) => {
  console.log("提交评价:", managerRequirementForm.value);
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {

      // 校验devs
      const validDevs = managerRequirementForm.value.devs.every((item: any) => {
        // 校验是否有评语为空
        if (isValidateString(item.mToDevTip)) {
          ElMessage.error("每条评论都必填，且不能为空");
          return false;
        }

        // 校验评分是否≤0
        if (
          isNaN(item.mToDevNumber) ||
          item.mToDevNumber < 0 || item.mToDevNumber == 0) {
          ElMessage.error("评分必填,且不能为0");
          return false;
        }

        // 如果所有校验通过
        return true;
      })

      console.log("校验结果：", validDevs);

      if (validDevs) {

        const { data } = await SaveManagerNoToDevRequirements(managerRequirementForm.value);
        if (data.code === 200) {
          ElMessage.success(data.msg);
          handleCloseEvaluateDialog();
          loading.value = true;
          getAllRequirements();
          loading.value = false;
        } else {
          ElMessage.error(data.msg);
          throw console.error(data.msg);
        }
      }


    } else {
      console.log("校验失败");
      throw console.error(fields);
    }
  })
};

onMounted(() => {
  getAllRequirements();
});
</script>
<style lang='scss' scoped>
.content-container {
  background-color: white;
  display: flex;
  flex-direction: column;
  padding: 10px;

  .table-requirement-name:hover {
    color: #409EFF;
    cursor: pointer;
  }

  .dialog-form-footer {
    width: 100%;
    text-align: right;
  }
}
</style>
